﻿using System;
using System.Collections.Generic;
using System.Linq;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.ExtensibleStorage;

namespace SectionSignAndFilled.StairsClearHeightDimension
{
	public class StairsDimXDataMgr
	{
		public static bool ElementHasGuid(Element element, Guid guid)
		{
			bool result = false;
			if (element != null)
			{
				IList<Guid> entitySchemaGuids = element.GetEntitySchemaGuids();
				result = entitySchemaGuids.Contains(guid);
			}
			return result;
		}

		public static void WriteDimensionXData(Element dimension, List<ElementId> arLineId)
		{
			Schema schema = Schema.Lookup(StairsDimXDataMgr.m_Guid);
			if (schema == null)
			{
				SchemaBuilder schemaBuilder = new SchemaBuilder(StairsDimXDataMgr.m_Guid);
				schemaBuilder.SetSchemaName(StairsDimXDataMgr.m_sDimSchemaName);
				schemaBuilder.SetReadAccessLevel((AccessLevel)1);
				schemaBuilder.AddSimpleField(StairsDimXDataMgr.m_sDimTypeField, typeof(int));
				schemaBuilder.AddArrayField(StairsDimXDataMgr.m_sDimLineField, typeof(ElementId));
				schema = schemaBuilder.Finish();
			}
			Entity entity = new Entity(schema);
			Field field = schema.GetField(StairsDimXDataMgr.m_sDimTypeField);
			entity.Set<int>(field, 1);
			field = schema.GetField(StairsDimXDataMgr.m_sDimLineField);
			entity.Set<IList<ElementId>>(field, arLineId);
			dimension.SetEntity(entity);
		}

		public static int ReadDimTypeXData(Element dimension)
		{
			int result = 0;
			if (!StairsDimXDataMgr.ElementHasGuid(dimension, StairsDimXDataMgr.m_Guid))
			{
				return result;
			}
			Schema schema = Schema.Lookup(StairsDimXDataMgr.m_Guid);
			if (schema != null)
			{
				Entity entity = dimension.GetEntity(schema);
				if (entity != null)
				{
					Field field = schema.GetField(StairsDimXDataMgr.m_sDimTypeField);
					if (field != null)
					{
						result = entity.Get<int>(field);
					}
				}
			}
			return result;
		}

		public static List<ElementId> ReadDimLineIdXData(Element dimension)
		{
			List<ElementId> result = new List<ElementId>();
			Schema schema = Schema.Lookup(StairsDimXDataMgr.m_Guid);
			if (schema != null)
			{
				Entity entity = dimension.GetEntity(schema);
				if (entity != null)
				{
					Field field = schema.GetField(StairsDimXDataMgr.m_sDimLineField);
					if (field != null)
					{
						result = entity.Get<IList<ElementId>>(field).ToList<ElementId>();
					}
				}
			}
			return result;
		}

		private static Guid m_Guid = new Guid("6CE023B9-3C83-4B9F-80EB-283829EED622");

		public static string m_sDimSchemaName = "StairsDimension";

		public static string m_sDimTypeField = "DimType";

		public static string m_sDimLineField = "lineIds";
	}
}
